<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

class Services extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = '*';
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';


    //获取服务传服务service_id
    public function service_details()
    {
        $service_id = $this->request->post('service_id');
        if (empty($service_id)) $this->error('请选择服务');
        $service_details = db('service')
            ->alias('s')
            ->join('service_type t', 's.type_id = t.id')
            ->where('s.id', $service_id)
            ->field('s.id,s.type_id,s.name,s.title,s.content,s.hours,s.price,s.status,s.views,s.order_num,t.name as type_name,t.title as type_title,s.images')
            ->find();
        if (empty($service_details)) {
            $this->error('服务不存在');
        }
        if(!empty($service_details['images'])){
            $service_details['images'] = explode(',',$service_details['images']);
        }
        $this->success('ok', $service_details);
    }

    /**
     * 搭子筛选返回字段
     */
    public function expert_search()
    {
        $qualifications = Db::name('category')
            ->where('type', 'qualification')
            ->where('status', 'normal')
            ->field('id,name')
            ->select();
        $qualification_options = array_merge(
            [['id' => 0, 'name' => '全部']],
            $qualifications
        );
        $filters = [
            'sort_options' => [
                ['id' => 1, 'name' => '默认排序'],
                ['id' => 2, 'name' => '离我最近'],
                ['id' => 3, 'name' => '最近新人'],
                ['id' => 4, 'name' => '我的关注']
            ],
            'age_options' => [
                ['id' => 0, 'name' => '全部'],
                ['id' => 1, 'name' => '80后'],
                ['id' => 2, 'name' => '90后'],
                ['id' => 3, 'name' => '00后']
            ],
            'gender_options' => [
                ['id' => 0, 'name' => '全部'],
                ['id' => 1, 'name' => '男'],
                ['id' => 2, 'name' => '女']
            ],
            'height_options' => [
                ['id' => 0, 'name' => '全部'],
                ['id' => 1, 'name' => '160cm以下'],
                ['id' => 2, 'name' => '160-165cm'],
                ['id' => 3, 'name' => '165-170cm'],
                ['id' => 4, 'name' => '170cm以上']
            ],
            'qualifications' => $qualification_options
        ];
        $this->success('ok', [ 'filters' => $filters]);
    }


    //获取搭子列表
    public function expert_list(){
        $param = $this->request->post();
        // 获取筛选参数
        $sort = isset($param['sort_options']) ? $param['sort_options'] : '1'; // 1 默认排序, 2 离我最近, 3 最近新人, 4 我的关注
        $age = isset($param['age_options']) ? $param['age_options'] : '0'; // 0 全部, 1 80后, 2 90后, 3 00后
        $gender = isset($param['gender']) ? $param['gender']:'0'; // 0 全部, 1 男, 2 女
        $qualification = isset($param['qualification']) ? $param['qualification']:'0'; // 全部  大专id
        $height = isset($param['height']) ? $param['height'] : '0'; // 身高0 全部 1 160cm以下, 2 160-165cm, 3 165-170cm, 4 170cm以上
        $lat = isset($param['lat']) ? $param['lat'] : ''; // 纬度
        $lng = isset($param['lng']) ? $param['lng'] : ''; // 经度
        $order_status = isset($param['order_status']) ? $param['order_status'] : '1'; // 0=离线，1=在线，3=忙碌
        if (empty($param['city_id'])){
            $this->error('城市id不能为空');
        }
        //服务id
        $service_id = isset($param['service_id']) ? $param['service_id'] : '0';;


        // 获取分页参数
        $page = isset($param['page']) ? (int)$param['page'] : 1;
        $perPage = isset($param['per_page']) ? (int)$param['per_page'] : 10;

        // 构建查询
        $query = Db::name('expert')

            ->where('status', 3)
        ->where('city_id',$param['city_id'])
        ->where('order_status',$order_status);

        // 年龄筛选（根据身份证号）
        if ($age !== '0') {
            switch ($age) {
                case '80s':
                    $query->where('id_number', 'like', '198%');
                    break;
                case '90s':
                    $query->where('id_number', 'like', '199%');
                    break;
                case '00s':
                    $query->where('id_number', 'like', '200%');
                    break;
            }
        }

        // 性别筛选
        if ($gender !== '0') {

            $query->where('gender', $gender);
        }

        // 学历筛选
        if ($qualification !== '0') {
            $query->where('qualification_id', $qualification);
        }

        // 服务筛选
        if (!empty($service_id)) {
            $query->join('expert_service es', 'es.user_id = ss_expert.user_id')
                ->where('es.service_id', $service_id);

        }
        // 身高筛选
        if ($height !== '0') {
            switch ($height) {
                case '1':
                    $query->where('height', '<', 160);
                    break;
                case '2':
                    $query->where('height', 'between', [160, 165]);
                    break;
                case '3':
                    $query->where('height', 'between', [165, 170]);
                    break;
                case '4':
                    $query->where('height', '>', 170);
                    break;
            }
        }


        // 1 默认排序, 2 离我最近, 3 最近新人, 4 我的关注
        // 排序
        switch ($sort) {
            case '2':
                // 离我最近，需要经纬度参数
                if (!empty($lat) && !empty($lng)) {
                    // 使用距离公式计算排序
                    $query->field("*, (POWER(lat-{$lat},2) + POWER(lng-{$lng},2)) AS distance")
                        ->order('distance', 'ASC');
                } else {
                    $query->order('createtime', 'DESC');
                }
                break;
            case '3':
                // 最近新人（按创建时间倒序）
                $query->order('createtime', 'DESC');
                break;
            case '4':
                // 我的关注（这里需要关联关注表，如果没有用户信息则按默认排序）
                $query->order('order_num', 'DESC');
                break;
            default:
                // 默认排序（按服务单数和浏览量）
                $query->order("ss_expert.id","DESC");
                break;
        }

        // 获取结果

        $experts = $query->page($page, $perPage)->field('ss_expert.*')->select();

        foreach ($experts as &$expert) {
            if (!empty($expert['birthday'])) {
                $birthday = new \DateTime($expert['birthday']);
                $today = new \DateTime();
                $age = $today->diff($birthday)->y;
                $expert['age'] = $age;
            } else {
                $expert['age'] = null;
            }
        }


        unset($expert);

        // 根据实际查询结果获取总数
        $total = count($experts);
        $result = [
            'list' => $experts,
            'pager' => [
                'page' => $page,
                'per_page' => $perPage,
                'total' => $total
            ],
        ];
        $this->success('ok', $result);

    }

    //用户关注
    public function user_follow(){
        $user_id = $this->auth->id; // 当前登录用户ID
        $expert_id = $this->request->post('expert_id');

        if (empty($expert_id)) {
            $this->error('参数错误');
        }
        if (empty($user_id)){
            $this->error('请登录');
        }
        // 检查是否已关注
        $follow = Db::name('follow')->where([
            'user_id' => $user_id,
            'expert_id' => $expert_id
        ])->find();

        if ($follow) {
            // 已关注则取消关注
            Db::name('follow')->where('user_id',$user_id)->where('expert_id',$expert_id)->delete();
            $this->success('已取消关注');
        } else {
            // 未关注则添加关注
            $data = [
                'user_id' => $user_id,
                'expert_id' => $expert_id,
                'createtime' => time()
            ];

            $result = Db::name('follow')->insert($data);
            if ($result) {
                $this->success('关注成功');
            } else {
                $this->error('关注失败');
            }
        }
    }


    //搭子详情
    // 获取专家详情
    public function expert_detail(){
        $user_id = $this->auth->id;

        if (empty($user_id)){
            $user_id = 0;
        }

        // 获取专家ID参数
        $expert_id = $this->request->post('expert_id');
        // 检查参数是否为空
        if (empty($expert_id)){
            $this->error('参数错误');
        }
        // 查询专家信息
        $expert = Db::name('expert')
            ->alias('e')
            ->join('city c', 'c.id=e.city_id')
            ->join('category ca', "FIND_IN_SET(ca.id, e.label_ids) > 0", 'LEFT')
            ->field("e.*,c.name as city_name,GROUP_CONCAT(ca.name) as label_name")
            ->where('e.id', $expert_id)
            ->group('e.id')
            ->find();

        // 获取专家技能信息
        $skills = Db::name('expert_service')
            ->alias('es')
            ->join('service s', 'es.service_id = s.id')
            ->field('s.id,s.name,s.title,s.price,s.image')
            ->where('es.expert_id', $expert_id)
            ->where('s.status', 1)
            ->select();

        // 将技能信息添加到专家信息中
        $expert['skills'] = $skills;

        // 根据生日计算年龄
        if (!empty($expert['birthday'])) {
            $birthday = new \DateTime($expert['birthday']);
            $today = new \DateTime();
            $age = $today->diff($birthday)->y;
            $expert['age'] = $age;

            // 根据生日计算星座
            $month = $birthday->format('m');
            $day = $birthday->format('d');

            // 星座判断
            if (($month == 3 && $day >= 21) || ($month == 4 && $day <= 19)) {
                $constellation = '白羊座';
            } elseif (($month == 4 && $day >= 20) || ($month == 5 && $day <= 20)) {
                $constellation = '金牛座';
            } elseif (($month == 5 && $day >= 21) || ($month == 6 && $day <= 21)) {
                $constellation = '双子座';
            } elseif (($month == 6 && $day >= 22) || ($month == 7 && $day <= 22)) {
                $constellation = '巨蟹座';
            } elseif (($month == 7 && $day >= 23) || ($month == 8 && $day <= 22)) {
                $constellation = '狮子座';
            } elseif (($month == 8 && $day >= 23) || ($month == 9 && $day <= 22)) {
                $constellation = '处女座';
            } elseif (($month == 9 && $day >= 23) || ($month == 10 && $day <= 23)) {
                $constellation = '天秤座';
            } elseif (($month == 10 && $day >= 24) || ($month == 11 && $day <= 22)) {
                $constellation = '天蝎座';
            } elseif (($month == 11 && $day >= 23) || ($month == 12 && $day <= 21)) {
                $constellation = '射手座';
            } elseif (($month == 12 && $day >= 22) || ($month == 1 && $day <= 19)) {
                $constellation = '摩羯座';
            } elseif (($month == 1 && $day >= 20) || ($month == 2 && $day <= 18)) {
                $constellation = '水瓶座';
            } elseif (($month == 2 && $day >= 19) || ($month == 3 && $day <= 20)) {
                $constellation = '双鱼座';
            } else {
                $constellation = '未知';
            }

            $expert['constellation'] = $constellation;
        } else {
            $expert['age'] = null;
            $expert['constellation'] = null;
        }


        // 计算粉丝数量（关注该专家的用户数量）
        $follower_count = Db::name('follow')
            ->where('expert_id', $expert_id)
            ->count();
        $expert['follower_count'] = $follower_count;

        // 判断当前用户是否关注了该专家
        $is_followed = Db::name('follow')
            ->where('user_id', $user_id)
            ->where('expert_id', $expert_id)
            ->find();
        $expert['is_followed'] = !empty($is_followed) ? 1 : 0;

        // 检查专家是否存在
        if (!$expert) {
            $this->error('专家不存在');
        }

        // 获取专家服务时间配置（从今天开始的日期）
        $service_times = Db::name('expert_service_time')
            ->where('user_id', $expert_id)
            ->where('date', '>=', date('Y-m-d'))
            ->select();

        // 获取已预约的订单时间 (已支付及之后状态的时间段不能再被预约)
        $ordered_times = Db::name('service_order')
            ->where('expert_user_id', $expert_id)
            ->where('service_date', '>=', date('Y-m-d'))
            ->where('status', 'in', [1, 2, 3, 4, 5, 6]) // 已支付及之后状态的时间段不能被预约
            ->field('service_date, service_time')
            ->select();

        // 处理可预约时间
        $available_times = [];
        // 遍历专家设置的服务时间
        foreach ($service_times as $service_time) {
            // 获取日期
            $date = $service_time['date'];
            // 初始化该日期的可预约时间数组
            $available_times[$date] = [
                'date' => $date,
                'available_time' => []
            ];

            // 解析可预约时间（JSON格式转数组）
            $time_slots = json_decode($service_time['time'], true);
            // 解析不可预约时间（JSON格式转数组）
            $cannot_time = json_decode($service_time['cannot_time'], true);

            // 获取当天已预约时间
            $ordered_for_date = array_filter($ordered_times, function($order) use ($date) {
                return $order['service_date'] == $date;
            });
            // 提取已预约的时间段
            $ordered_time_slots = array_column($ordered_for_date, 'service_time');

            // 获取当前时间（如果日期是今天，则需要过滤当前时间之前的时段）
            $current_time = date('H:i');
            $is_today = $date == date('Y-m-d');

            // 过滤可预约时间
            if (is_array($time_slots)) {
                // 遍历所有可预约时间段
                foreach ($time_slots as $time_slot) {
                    // 如果是今天，且时间段早于当前时间，则跳过
                    if ($is_today && $time_slot < $current_time) {
                        continue;
                    }

                    // 排除不可预约时间
                    if (is_array($cannot_time) && in_array($time_slot, $cannot_time)) {
                        continue;
                    }

                    // 排除已预约时间
                    if (in_array($time_slot, $ordered_time_slots)) {
                        continue;
                    }

                    // 将可用时间段添加到结果数组
                    $available_times[$date]['available_time'][] = $time_slot;
                }
            }
        }
        
        // 获取最早可预约的时间
        $earliest_date = null;
        $earliest_time_slot = null;
        
        // 按日期排序 available_times 数组
        ksort($available_times);
        
        // 遍历排序后的日期，找到第一个有可预约时间的日期和时间段
        foreach ($available_times as $date => $time_info) {
            if (!empty($time_info['available_time'])) {
                $earliest_date = $date;
                // 对时间进行排序，确保获取最早的时间段
                sort($time_info['available_time']);
                $earliest_time_slot = $time_info['available_time'][0];
                break;
            }
        }
        
        // 将最早可预约时间信息添加到专家信息中
        $expert['earliest_available'] = [
            'date' => $earliest_date,
            'time' => $earliest_time_slot
        ];



        // 返回成功响应
        $this->success('ok', $expert);
    }



    //添加用户地址
    public function order_address(){
        $user_id = $this->auth->id;
        if (empty($user_id)){
            $this->error('请登录');
        }
        $name = $this->request->post('name');
        $gender = $this->request->post('gender');
        $phone = $this->request->post('mobile');
        $address = $this->request->post('address');
        $lat = $this->request->post('lat');
        $lng = $this->request->post('lng');
        $address_info =$this->request->post('address_info');
        $is_default=$this->request->post('is_default',0);
        if ($is_default==1){
            Db::name('address')->where('user_id',$user_id)->update(['is_default'=>0]);
        }
        $address_data =[
            'user_id'=>$user_id,
            'name'=>$name,
            'gender'=>$gender,
            'mobile'=>$phone,
            'address'=>$address,
            'lat'=>$lat,
            'lng'=>$lng,
            'address_info'=>$address_info,
            'is_default'=>$is_default,
            'createtime'=>time()
        ];
        $address = Db::name('address')->insert($address_data);
        if ($address){
            $this->success('添加成功');
        }else{
            $this->error('添加失败');
        }
    }

    //获取用户地址
    public function get_address(){
        $user_id = $this->auth->id;
        if (empty($user_id)){
            $this->error('请登录');
        }
        $address = Db::name('address')->where('user_id',$user_id)->order("is_default desc id desc")->select();
        $this->success('获取用户地址成功',$address);
    }


    /**
     * 获取达人可预约时间
     */
    public function get_available_times() {
        $expert_id = $this->request->post('expert_id');
        if (empty($expert_id)) {
            $this->error('参数错误');
        }

        // 检查专家是否存在
        $expert = Db::name('expert')->where('id', $expert_id)->find();
        if (!$expert) {
            $this->error('专家不存在');
        }

        // 获取专家服务时间配置（从今天开始的日期）
        $service_times = Db::name('expert_service_time')
            ->where('user_id', $expert_id)
            ->where('date', '>=', date('Y-m-d'))
            ->select();

        // 获取已预约的订单时间 (已支付及之后状态的时间段不能再被预约)
        $ordered_times = Db::name('service_order')
            ->where('expert_user_id', $expert_id)
            ->where('service_date', '>=', date('Y-m-d'))
            ->where('status', 'in', [1, 2, 3, 4, 5, 6])
            ->field('service_date, service_time')
            ->select();

        // 处理可预约时间
        $available_times = [];
        foreach ($service_times as $service_time) {
            $date = $service_time['date'];
            $available_times[$date] = [
                'date' => $date,
                'available_time' => []
            ];

            // 解析可预约时间（JSON格式转数组）
            $time_slots = json_decode($service_time['time'], true);
            // 解析不可预约时间（JSON格式转数组）
            $cannot_time = json_decode($service_time['cannot_time'], true);

            // 获取当天已预约时间
            $ordered_for_date = array_filter($ordered_times, function($order) use ($date) {
                return $order['service_date'] == $date;
            });
            // 提取已预约的时间段
            $ordered_time_slots = array_column($ordered_for_date, 'service_time');

            // 过滤可预约时间
            if (is_array($time_slots)) {
                // 遍历所有可预约时间段
                foreach ($time_slots as $time_slot) {
                    // 排除不可预约时间
                    if (is_array($cannot_time) && in_array($time_slot, $cannot_time)) {
                        continue;
                    }

                    // 排除已预约时间
                    if (in_array($time_slot, $ordered_time_slots)) {
                        continue;
                    }

                    // 将可用时间段添加到结果数组
                    $available_times[$date]['available_time'][] = $time_slot;
                }
            }
        }

        // 返回可预约时间
        $this->success('获取成功', array_values($available_times));
    }


    /**
     * 获取搭子的技能
     */
    public function get_skill(){
        $expert_id = $this->request->post('expert_id');
        if (empty($expert_id)){
            $this->error('参数错误');
        }
        $skill = Db::name('expert_service')
            ->alias('es')
            ->join('service s','es.service_id=s.id')
            ->where('es.expert_id',$expert_id)
            ->select();
        // 返回可预约时间
        $this->success('获取成功',$skill);
    }


    /**
     * 创建服务订单
     */
    public function create_order()
    {
        $user_id = $this->auth->id;
        if (empty($user_id)) {
            $this->error('请登录');
        }
        // 获取参数
        $expert_id = $this->request->post('expert_id');
        $service_date = $this->request->post('service_date');
        $service_time = $this->request->post('service_time');
        $address_id = $this->request->post('address_id');
        $services = $this->request->post('services/a'); // 服务数组，包含服务ID和数量
        $driver_type = $this->request->post('driver_type', 1); // 出行方式:1=出租车
        // 计算车费
        $fare_price= $this->request->post('fare_price'); //车费总价
        $total_distance = $this->request->post('total_distance'); //总距离
        $start_num = $this->request->post('start_num'); //起步公里数
        $start_price = $this->request->post('start_price'); //起步价
        $other_price = $this->request->post('other_price'); //超出部分每公里价格


        // 参数验证
        if (empty($expert_id)) {
            $this->error('请选择服务达人');
        }

        if (empty($service_date) || empty($service_time)) {
            $this->error('请选择服务时间');
        }

        if (empty($address_id)) {
            $this->error('请选择服务地址');
        }

        if (empty($services) || !is_array($services)) {
            $this->error('请选择服务项目');
        }

        // 检查达人是否存在
        $expert = Db::name('expert')->where('id', $expert_id)->where('status', 3)->find();
        if (!$expert) {
            $this->error('服务达人不存在或未通过审核');
        }

        // 检查服务时间是否可用
        $ordered_times = Db::name('service_order')
            ->where('expert_user_id', $expert_id)
            ->where('service_date', $service_date)
            ->where('service_time', $service_time)
            ->where('status', 'in', [1, 2, 3, 4, 5, 6])
            ->find();

        if ($ordered_times) {
            $this->error('该时间段已被预约，请选择其他时间');
        }

        // 检查地址是否存在
        $address = Db::name('address')->where('id', $address_id)->where('user_id', $user_id)->find();
        if (!$address) {
            $this->error('地址信息不存在');
        }

        // 计算服务费用
        $total_price = 0;
        $service_details = [];
        foreach ($services as $service) {

             $service_id = $service['service_id'];

            $num = isset($service['num']) ? $service['num'] : 1;

            // 获取服务信息
            $service_info = Db::name('service')->where('id', $service_id)->find();

            if (!$service_info) {
                $this->error("服务项目不存在:{$service_id}");
            }

            $unit_price = $service_info['price'];
            $price = $unit_price * $num;

            $service_details[] = [
                'service_id' => $service_id,
                'unit_price' => $unit_price,
                'num' => $num,
                'price' => $price,
                'service_date' => $service_date,
                'service_time' => $service_time
            ];

            $total_price += $price;
        }



        // 订单总金额
        $real_price = $total_price + $fare_price;


        Db::startTrans();
        try {
            // 生成订单号
            $order_sn = date('YmdHis') . str_pad($user_id, 6, '0', STR_PAD_LEFT) . rand(10, 99);

            // 创建订单主表
            $order_data = [
                'order_sn' => $order_sn,
                'user_id' => $user_id,
                'expert_user_id' => $expert_id,
                'price' => $total_price,
                'fare_price' => $fare_price,
                'real_price' => $real_price,
                'status' => 0, // 未支付
                'service_date' => $service_date,
                'service_time' => $service_time,
                'createtime' => time(),
                'updatetime' => time()
            ];

            $order_id = Db::name('service_order')->insertGetId($order_data);

            // 创建订单详情
            foreach ($service_details as $detail) {
                $detail_data = [
                    'order_id' => $order_id,
                    'service_id' => $detail['service_id'],
                    'expert_user_id' => $expert_id,
                    'unit_price' => $detail['unit_price'],
                    'num' => $detail['num'],
                    'price' => $detail['price'],
                    'status' => 0, // 未支付
                    'service_date' => $detail['service_date'],
                    'service_time' => $detail['service_time'],
                    'createtime' => time(),
                    'updatetime' => time()
                ];
                Db::name('service_order_detail')->insert($detail_data);
            }

            // 创建订单地址
            $order_address_data = [
                'order_id' => $order_id,
                'user_id' => $user_id,
                'address_id' => $address_id,
                'mobile' => $address['mobile'],
                'name' => $address['name'],
                'gender' => $address['gender'],
                'address' => $address['address'],
                'lat' => $address['lat'],
                'lng' => $address['lng'],
                'address_info' => $address['address_info'],
                'expert_address' => $expert['address'],
                'expert_lat' => $expert['lat'],
                'expert_lng' => $expert['lng'],
                'driver_type' => $driver_type,
                'distance' =>$total_distance, // 实际距离需要通过地图API计算
                'start_num' => $start_num,
                'start_price' => $start_price,
                'other_price' =>$other_price,
                'price' =>  $fare_price,
                'createtime' => time(),
                'updatetime' => time()
            ];
            Db::name('service_order_address')->insert($order_address_data);

            // 提交事务
            Db::commit();


            // 准备返回数据
            $return_data = [
                'order_id' => $order_id,
                'order_sn' => $order_sn,
                'real_price' => $real_price
            ];

          $this->success('订单创建成功', $return_data);

        }catch (\think\Exception\DbException $exception) {
            // 只有在事务未提交时才回滚
            Db::rollback();

            $this->error('订单创建失败: ' . $exception->getMessage());
        }
    }

    /**
     * 计算车费
     */
    public function calculate_fare()
    {
        $address_id = $this->request->post('address_id');
        $expert_id = $this->request->post('expert_id');
        $user_id = $this->auth->id;


        if(empty($user_id)){
            $this->error('请登录');
        }
        
        // 获取地址信息
        $address = Db::name('address')->where('id', $address_id)->where('user_id', $user_id)->find();
        if (!$address) {
            $this->error('地址信息不存在');
        }
    
        // 获取专家信息及其所在城市的计费标准
        $expert = Db::name('expert')
            ->alias('e')
            ->join('city c', 'e.city_id = c.id')
            ->field('e.*, c.start_num, c.start_price, c.other_price')
            ->where('e.id', $expert_id)
            ->where('e.status', 3)
            ->find();
        if (!$expert) {
            $this->error('专家信息不存在或未通过审核');
        }
        $user_lat = $address['lat'];
        $user_lng = $address['lng'];
        $expert_lat = $expert['lat'];
        $expert_lng = $expert['lng'];
        if (empty($expert_lat)){
            $this->error('达人地址信息不存在');
        }
        if (empty($expert_lng)){
            $this->error('达人地址信息不存在');
        }
        
        // 这里应该使用地图API计算实际路程距离
        // 暂时使用直线距离（后续建议改为地图API）

        $distance = sqrt(pow($user_lat - $expert_lat, 2) + pow($user_lng - $expert_lng, 2)) * 100;
        
        // 使用城市的计费标准
        $start_num = $expert['start_num'];     // 起步公里数
        $start_price = $expert['start_price']; // 起步价
        $other_price = $expert['other_price']; // 超出部分每公里价格
        
        // 计算费用：起步价 + 超出部分的费用
        if ($distance <= $start_num) {
            $fare = $start_price;
        } else {
            $fare = $start_price + ($distance - $start_num) * $other_price;
        }
        
        $fares = ceil($fare * 100) / 100;
        $this->success('计算金额', [
            'total_distance' => round($distance, 1), // 总距离
            'start_num' => $start_num,               // 起步公里数
            'start_price' => $start_price,           // 起步价
            'other_price' => $other_price,           // 超出部分每公里价格
            'total_price' => $fares                  // 总价
        ]);
    }
    //订单更新
    public function update_order(){
        $order_id=$this->request->post('order_id');
       
        $order=Db::name('service_order')->where('id',$order_id)->find();
        if(!$order){
            $this->error('订单不存在');
        }
        $order['status']=1;
        $res['status']=1;
        Db::name('service_order')->where('id',$order_id)->update($order);
        Db::name('service_order_detail')->where('id',$order_id)->update($res);
        $this->success('更新订单状态成功');
    }

}